<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'wms:jh:pick:jhPickMain:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="80%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span class="mr-1" > {{ getTitle.value }} </span>
      <DictLabel v-if="record.jhStatus" :dictType="'jh_main_status'" :dictValue="record.jhStatus" />
    </template>
    <BasicForm @register="registerForm">
      <template #jhPickDetailsList>
        <BasicTable
          @register="registerJhPickDetailsTable"
          @row-click="handleJhPickDetailsRowClick"
       >
        <template #summary>
          <Table.Summary fixed>
            <Table.Summary.Row>
              <Table.Summary.Cell :index="0" :col-span="1" :style="{ textAlign: 'center', fontWeight: 'bold'}"
                >合计</Table.Summary.Cell
              >
              <Table.Summary.Cell :index="2" :col-span="4"></Table.Summary.Cell>
              <Table.Summary.Cell :index="5" :style="{ textAlign: 'right', fontWeight: 'bold' }">
                {{ totalIqty.sumfqty }}</Table.Summary.Cell
              >
              <Table.Summary.Cell :index="6" :style="{ textAlign: 'right', fontWeight: 'bold' }">
                {{ totalIqty.sumfweight }}</Table.Summary.Cell
              >
              <Table.Summary.Cell :index="7" :col-span="2"></Table.Summary.Cell>

              <Table.Summary.Cell :index="9" :style="{ textAlign: 'right', fontWeight: 'bold' }">
                {{ totalIqty.sumJhQty }}</Table.Summary.Cell>
            </Table.Summary.Row>
          </Table.Summary>
        </template>
      </BasicTable>
        <!-- <a-button
          class="mt-2"
          @click="handleJhPickDetailsAdd"
          v-auth="'wms:jh:pick:jhPickMain:edit'"
        >
          <Icon icon="i-ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button> -->
      </template>
    </BasicForm>
    <hwList @register="registerHwDrawer" />
    <invList @register="registerInvDrawer" />
    <Modal @register="registerModal" @success="handleSuccess" />
  </BasicDrawer>
</template>
<script lang="ts" setup name="ViewsWmsJhPickJhPickMainForm">
  import { ref, unref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner, useDrawer } from '/@/components/Drawer';
  import { JhPickMain, jhPickMainSave, jhPickMainForm } from '/@/api/wms/jh/pick/jhPickMain';
  import { DictLabel } from '/@/components/Dict';
  import hwList from './hwList.vue';
  import invList from './invList.vue';
  import { Table } from 'ant-design-vue';
  import Modal from './Modal.vue';
  import { useModal } from '/@/components/Modal';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('wms.jh.pick.jhPickMain');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<JhPickMain>({} as JhPickMain);
  const loadingRef = ref(false);

  const getTitle = computed(() => ({
    icon: meta.icon || 'i-ant-design:book-outlined',
    // value: record.value.isNewRecord ? t('新增拣货单主表') : t('编辑拣货单主表'),
    value: t('拣货单'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('公司名称'),
      field: 'company.companyName',
      component: 'Input',
      componentProps: {
        maxlength: 255,
      },
      dynamicDisabled: true,
    },
    {
      label: t('拣货单号'),
      field: 'djno',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      rules: [
        { required: true },
        { pattern: /^[a-zA-Z0-9_]*$/, message: t('请输入字母数字下划线') },
      ],
    },
    {
      label: t('拣货日期'),
      field: 'date',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        showTime: false,
      },
      required: true,
      dynamicDisabled: true,
    },

    // {
    //   label: t('拣货状态'),
    //   field: 'jhStatus',
    //   component: 'Select',
    //   componentProps: {
    //     dictType: 'jh_main_status',
    //   },
    //   dynamicDisabled: true,
    // },
    {
      label: t('仓库'),
      field: 'basWare.cwhname',
      component: 'Input',
      componentProps: {
        maxlength: 255,
      },
      dynamicDisabled: true,
    },
    
    {
      label: t('拣货方式'),
      field: 'type',
      component: 'Select',
      componentProps: {
        dictType: 'jh_type',
      },
      required: true,
    },
    {
      label: t('制单人'),
      field: 'createByName',
      component: 'Input',
      componentProps: {
        maxlength: 255,
      },
      dynamicDisabled: true,
    },
    {
      label: t('公司编码'),
      field: 'companyCode',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      dynamicDisabled: true,
      ifShow: false,
    },   
    {
      label: t('拣货明细'),
      field: 'jhPickDetailsList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'jhPickDetailsList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 8, md: 24 },
  });

  const [registerHwDrawer, { openDrawer:openHwDrawer }] = useDrawer();
  const [registerInvDrawer, { openDrawer:openInvDrawer  }] = useDrawer();
  const [registerJhPickDetailsTable, jhPickDetailsTable] = useTable({
    actionColumn: {
      width: 150,
      actions: (record: Recordable) => [
        {
          // icon: 'i-ant-design:delete-outlined',
          label:'查看货位',
          onClick: handleHwList.bind(this, { id: record.id }),
          auth: 'wms:jh:pick:jhPickMain:edit',
        },
        {
          // icon: 'i-ant-design:delete-outlined',
          label:'查看商品',
          color: 'success',
          onClick: handleInvList.bind(this, { id: record.id, jhStatus: record.jhStatus }),
          auth: 'wms:jh:pick:jhPickMain:edit',
        },
        // {
        //   // icon: 'i-ant-design:delete-outlined',
        //   label:'修改数量',
        //   onClick: handlefqty.bind(this, record),
        //   auth: 'wms:jh:pick:jhPickMain:edit',
        // },
        // {
        //   icon: 'i-ant-design:delete-outlined',
        //   color: 'error',
        //   title: t('删除商品'),
        //   popConfirm: {
        //     title: t('是否确认删除商品'),
        //     confirm: handleJhPickDetailsDelete.bind(this, record),
        //   },
        //   auth: 'wms:jh:pick:jhPickMain:edit',
        // },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
    showCustomSummary: true,
  });

  async function setJhPickDetailsTableData(_res: Recordable) {
    jhPickDetailsTable.setColumns([
    {
        title: t('拣货状态'),
        dataIndex: 'jhStatus',
        width: 100,
        align: 'left',
        editRow: false,
        dictType: 'jh_main_status',
        editComponent: 'Select',
        editComponentProps: {
          dictType: 'jh_main_status',
        },
        editRule: false,
        // fixed: 'right',
      },
      {
        title: t('商品编码'),
        dataIndex: 'basInv.viewCode',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
      },
      {
        title: t('商品名称'),
        dataIndex: 'basInv.invName',
        width: 230,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
      },
      {
        title: t('形象刊'),
        dataIndex: 'freeVO.cfree1',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 255,
        },
        editRule: false,
      },
      {
        title: t('数量'),
        dataIndex: 'fqty',
        width: 80,
        align: 'right',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 16,
        },
        editRule: false,
        showSummary: true,
      },
      {
        title: t('重量'),
        dataIndex: 'fweight',
        width: 100,
        align: 'right',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 16,
        },
        editRule: false,
        showSummary: true,
      },
      {
        title: t('仓库名称'),
        dataIndex: 'basWare.cwhname',
        key: 'a.wh_code',
        // sorter: true,
        width: 100,
        align: 'left',
      },
      {
        title: t('货位'),
        dataIndex: 'cposNames',
        width: 130,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 2000,
        },
        editRule: false,
      },
      {
        title: t('累计拣货数'),
        dataIndex: 'sumJhQty',
        width: 100,
        align: 'right',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 16,
        },
        editRule: false,
      },

      {
        title: t('自由项2'),
        dataIndex: 'cfree2',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 255,
        },
        editRule: false,
        ifShow: false,
      },
      {
        title: t('自由项3'),
        dataIndex: 'cfree3',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 255,
        },
        editRule: false,
        ifShow: false,
      },
      
    ]);
    jhPickDetailsTable.setTableData(record.value.jhPickDetailsList || []);
  }

  function handleJhPickDetailsRowClick(record: Recordable) {
    // record.onEdit?.(true, false);
  }

  function handleJhPickDetailsAdd() {
    jhPickDetailsTable.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
    });
  }

  function handleHwList(record: Recordable) {
    openHwDrawer(true, record);
  }

  function handleInvList(record: Recordable) {
    openInvDrawer(true, record);
  }
  

  function handleJhPickDetailsDelete(record: Recordable) {
    // jhPickDetailsTable.deleteTableDataRecord(record);
  }

  function handlefqty(record: Recordable) {
    // jhPickDetailsTable.deleteTableDataRecord(record);
    openModal(true,record)
  }


  async function getJhPickDetailsList() {
    let jhPickDetailsListValid = true;
    let jhPickDetailsList: Recordable[] = [];
    for (const record of jhPickDetailsTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        jhPickDetailsListValid = false;
      }
      jhPickDetailsList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of jhPickDetailsTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      jhPickDetailsList.push({
        ...record,
        status: '1',
      });
    }
    if (!jhPickDetailsListValid) {
      throw { errorFields: [{ name: ['jhPickDetailsList'] }] };
    }
    return jhPickDetailsList;
  }

  const [registerModal, { openModal }] = useModal();
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await jhPickMainForm(data);
    record.value = (res.jhPickMain || {}) as JhPickMain;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setJhPickDetailsTableData(res);
    updateSchema([
      {
        field: 'djno',
        componentProps: {
          disabled: !record.value.isNewRecord,
        },
      },
    ]);
    setDrawerProps({ loading: false });
  });

  async function handleValidate(_event: any, formData: any) {
    try {
      const data = await validate();
      formData(true, data); // 将表单数据传递给 BpmButton
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    }
  }

  async function handleSubmit(event: any) {
    try {
      loadingRef.value = true;
      const data = event?.formData || (await validate()); // 接受 BpmButton 传递过来的表单数据
      //data.status = record.value.status; // 提交状态
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        djno: record.value.djno,
      };
      data.jhPickDetailsList = await getJhPickDetailsList();
      // console.log('submit', params, data, record);
      const res = await jhPickMainSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      loadingRef.value = false;
      setDrawerProps({ confirmLoading: false });
    }
  }

  const totalIqty = computed(() => {
    // 计算总报工数
    const tableData = jhPickDetailsTable.getDataSource();
    // const tableData = getDataSource.value;
    let sumfqty = tableData.reduce((total, item) => total + (item.fqty || 0), 0);
    let sumfweight = tableData.reduce((total, item) => total + (item.fweight || 0), 0);
    let sumJhQty = tableData.reduce((total, item) => total + (item.sumJhQty || 0), 0);
    return {
      sumfqty,
      sumfweight: sumfweight.toFixed(2),
      sumJhQty,
    };
  });

  async function handleSuccess() {
    emit('success');
  }
</script>
